package com.apgblogs.springbootstudy.controller;

import com.apgblogs.springbootstudy.validator.UserValidator;
import com.apgblogs.springbootstudy.vo.UserVo;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author xiaomianyang
 * @description
 * @date 2019-07-09 16:26
 */
@RestController
@RequestMapping("validate")
public class ValidateController {

    @InitBinder
    public void initBinder(WebDataBinder binder){
        binder.setValidator(new UserValidator());
    }

    @PostMapping("user")
    public Map<String,Object> validate(@Valid @RequestBody UserVo userVo, Errors errors){
        Map<String,Object> errorMap=new HashMap<>();
        List<ObjectError> objectErrorList=errors.getAllErrors();
        for(ObjectError objectError:objectErrorList){
            String key=null;
            String msg=null;
            if(objectError instanceof FieldError){
                FieldError fieldError=(FieldError)objectError;
                key=fieldError.getField();
            }else{
                key=objectError.getObjectName();
            }
            msg=objectError.getDefaultMessage();
            errorMap.put(key,msg);
        }
        return errorMap;
    }
}
